package com.heima.behavior.service.impl;
import com.alibaba.fastjson.JSON;
import com.heima.constants.message.HotArticleConstants;
import com.heima.model.mess.app.NewBehaviorDTO.BehaviorType;

import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.mess.app.NewBehaviorDTO;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //阅读行为记录
    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        //查询是否存在阅读行为
        Query query = Query.query(Criteria.where("entryId").is(dto.getEquipmentId().toString()).and("articleId").is(dto.getArticleId()));
        ApReadBehavior apReadBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        //非空判断
        if (apReadBehavior != null) {
            //存在,次数加1保存回数据库
            Update update = new Update();
            update.set("count", (short) (apReadBehavior.getCount() + 1)).set("updatedTime",new Date());
            mongoTemplate.updateMulti(query, update, ApReadBehavior.class);
        }else{
            //不存在,新增
            apReadBehavior = new ApReadBehavior();
            apReadBehavior.setCount((short)1);
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setEntryId(dto.getEquipmentId().toString());
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setUpdatedTime(new Date());
            mongoTemplate.save(apReadBehavior);
        }
        //创建NewBehaviorDTO,发送MQ消息
        NewBehaviorDTO newBehaviorDTO = new NewBehaviorDTO();
        newBehaviorDTO.setType(BehaviorType.VIEWS);
        newBehaviorDTO.setArticleId(dto.getArticleId());
        newBehaviorDTO.setAdd(1);
        //发送MQ消息
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(newBehaviorDTO));
        //响应调用者
        return ResponseResult.okResult();
    }
}
